/**
 * 
 */
package com.qjs.smterp.model.primefaces;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.primefaces.model.LazyDataModel;
import org.primefaces.model.SortOrder;

import com.qjs.smterp.model.Instock;

/**
 * @author tudd
 *
 */
public class LazyInstockDataModel extends LazyDataModel<Instock> {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public List<Instock> dInstocks;
	
	public LazyInstockDataModel(List<Instock> dInstocks) {
		this.dInstocks = dInstocks;
	}

	 @Override  
	    public Instock getRowData(String rowKey) {  
	        for(Instock instock : dInstocks) {  
	            if(instock.getInstockCode().equals(rowKey))  
	                return instock;  
	        }  
	  
	        return null;  
	    }  
	  
	    @Override  
	    public Object getRowKey(Instock instock) {  
	        return instock.getInstockCode();
	    }  
	    
	@Override
	public List<Instock> load(int first, int pageSize, String sortField, SortOrder sortOrder,
			Map<String, String> filters) {
		// TODO Auto-generated method stub
		List<Instock> data = new ArrayList<Instock>();
		//filter
		for(Instock instock : dInstocks) {  
            boolean match = true;  
            for(Iterator<String> it = filters.keySet().iterator(); it.hasNext();) {  
                try {  
                    String filterProperty = it.next();  
                    String filterValue = filters.get(filterProperty);  
                    String fieldValue = String.valueOf(instock.getClass().getField(filterProperty).get(instock));  
  
                    if(filterValue == null || fieldValue.startsWith(filterValue)) {  
                        match = true;  
                    }  
                    else {  
                        match = false;  
                        break;  
                    }  
                } catch(Exception e) {  
                    match = false;  
                }   
            }  
  
            if(match) {  
                data.add(instock);  
            }  
        }  
		//sort
		 if(sortField != null) {  
	            Collections.sort(data, new LazySorter(sortField, sortOrder));  
	        }  
	  
	        //rowCount  
	        int dataSize = data.size();  
	        this.setRowCount(dataSize);  
	  
	        //paginate  
	        if(dataSize > pageSize) {  
	            try {  
	                return data.subList(first, first + pageSize);  
	            }  
	            catch(IndexOutOfBoundsException e) {  
	                return data.subList(first, first + (dataSize % pageSize));  
	            }  
	        }  
	        else {  
	            return data;  
	        }  
	}

}
